<?php

// +----------------------------------------------------------------------
// | Static Plugin for ThinkAdmin
// +----------------------------------------------------------------------
// | 版权所有 2014~2024 ThinkAdmin [ thinkadmin.top ]
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/think-plugs-static
// | github 代码仓库：https://github.com/zoujingli/think-plugs-static
// +----------------------------------------------------------------------

namespace app\index\controller;

use think\facade\Db;
use think\Exception;
use think\facade\Log;


class Member extends Base
{
    protected $member;

    public function __construct()
    {
        $this->member = session('member');
    }

    public function home(){
        //$uid = 362;//这个是自己得
        $id = request()->param('id');
        $my_id = $this->member['uid'];
        $uid = $id;
        if(empty($uid)){
            $uid = $my_id;
        }else{
            //添加访问记录
            $data['one']= $id;//被访问得人
            $data['tow']= $my_id;//访问人
            $data['addtime']=date('Y-m-d H:i:s');
            $data['status']=1;
            Db::table('xj_visit')->insertGetId($data);
        }
        $this->ziliao=Db::table('xj_member')->field('uid,nickname,intr,avatar')->where('uid',$uid)->find();

        //访问
        $visit_sql = Db::name('xj_visit')
                    ->alias('v')
                    ->join('xj_member m', 'v.tow = m.uid') //
                    ->where('v.one', $uid)
                    ->field('v.*, m.nickname, m.avatar') // Select needed fields
                    ->order('v.addtime', 'DESC')
                    ->group('v.tow');
        $this->visit_num= $visit_sql->count();
        //echo Db::getLastSql();
        $visit = $visit_sql
                ->limit(12)
                ->select()
                ->toArray();



        //信息动态
        $list= Db::name('xj_comment')->where(['author_id'=>$uid,'is_display'=>1])->order("id desc")->select();//别人@你

        //你@别人
        $list1 = Db::name('xj_comment')
                ->alias('c')
                ->join('xj_member m', 'c.author_id = m.uid') // 关联用户表
                ->where('c.critic_id', $uid)
                ->field('c.*, m.nickname') // 同时获取评论和用户昵称
                ->order('c.id', 'desc')
                ->select()
                ->toArray();

        //发布得文章
        $article = Db::name('xj_news')
                    ->alias('n')
                    ->leftJoin('xj_comment c', 'n.id = c.pid AND c.is_level = 0 AND c.is_display = 1')
                    ->field('n.id, n.title, n.published, n.status, n.access, n.content,n.add_time, COUNT(c.id) as comment_num')
                    ->where(['n.mid' => $uid, 'n.status' => 1])
                    ->group('n.id')
                    ->order('n.id','DESC')
                    ->paginate(10);


        $this->assign("author_id", $id);//作者id 有表示前端页面不能显示文章
        $this->assign("visit", $visit);
        $this->assign("list", $list);
        $this->assign("list1", $list1);
        $this->assign("article", $article);
        $this->siteFetch('member/home');
    }


    //文章列表
    public function memberCenter(){
        $list= Db::table('xj_news')
            ->field('id,title,add_time,status,access')
            ->where(['mid'=>$this->member['uid']])
            ->where('status', 'in', [0,1,2,3])
            ->order("id desc")
            ->paginate(10);
        $this->assign("list", $list);
        $this->siteFetch('member/memberCenter');
    }

    //提交文章
    public function articleSave(){
        $id = request()->param('id');
        $cid = request()->param('cid');
        $subject = request()->param('title');
        $content = request()->param('content');
        $summary = request()->param('summary');
        $img = request()->param('img');
        if($content == ''){
            return arrayFail('客官，,这家伙忘记填写内容了！！！');
        }
        if($cid == ''){
            return arrayFail('客官，,这家伙忘记选择分类了！！！');
        }
        $data = [
            'cid'=> $cid,
            'title'=> $subject,
            'keywords'=> $subject,
            'summary'=> $summary,
            'content'=> $content,
        ];

        //print_r($id);die;
        if(!empty($id)){
            Db::table('xj_news')->where('id',$id)->update($data);
        }else{
            $data['mid'] = $this->member['uid'];
            $data['add_time'] = date('Y-m-d H:i:s');
            Db::table('xj_news')->insertGetId($data);
        }

        return arraySuccess('客官,成功了!!!');
        //$data['content']=html_entity_decode($data1['content']);
        //$data['image_id']=$image_id;
    }

    //添加编辑文章
    public function articleForm(){
        $id = request()->param('id');
        $list= Db::table('xj_news')->field('id,cid,title,content,summary')->where('id',$id)->find();
        $this->assign("list", $list);
        $this->siteFetch('member/articleForm');
    }

    //删除文章
    public function articleDel(){
        $id = request()->param('id');
        $status = request()->param('status');
        if(!$id){
            return arrayFail('客官，,这家伙不肯这么做！！！');
        }
        if(!$status){
            return arrayFail('客官，,这家伙不肯这么做呢！！！');
        }

        Db::table('xj_news')
            ->where('id', $id)
            ->update(['status' => $status]);
        return arraySuccess('客官,成功了!!!');
    }


    //love列表
    public function loveList(){
        $list= Db::table('xj_love')
            ->field('*')
            ->where(['mid'=>$this->member['uid']])
            ->where('status', 'in', [0,1,2,3])
            ->order("id desc")
            ->paginate(10);
        $this->assign("list", $list);
        $this->siteFetch('member/loveList');
    }

    //编辑新增
    public function loveForm(){
        $id = request()->param('id');
        $list= Db::table('xj_love')->field('id,one,two,three')->where('id',$id)->find();
        $this->assign("list", $list);
        $this->siteFetch('member/loveForm');
    }

    //提交
    public function loveSave(){
        $id = request()->param('id');
        $one = request()->param('one');
        $two = request()->param('two');
        $three = request()->param('three');
        $data = [
            'one' =>$one,
            'two' =>$two,
            'three' =>$three,
        ];
        if(!empty($id)){
            Db::table('xj_love')->where('id',$id)->update($data);
        }else{
            $data['mid'] = $this->member['uid'];
            $data['add_time'] = date('Y-m-d H:i:s');
            Db::table('xj_love')->insertGetId($data);
        }
        return arraySuccess('客官,成功了!!!');
    }

    //删除
    public function loveDel(){
        $id = request()->param('id');
        $status = request()->param('status');
        if(!$id){
            return arrayFail('客官，,这家伙不肯这么做！！！');
        }
        if(!$status){
            return arrayFail('客官，,这家伙不肯这么做呢！！！');
        }

        Db::table('xj_love')
            ->where('id', $id)
            ->update(['status' => $status]);
        return arraySuccess('客官,成功了!!!');
    }

    //设置
    public function setting(){
        $list= Db::table('xj_member')->field('uid,penname,email,qq,mobile,intr,avatar')->where(['uid'=>$this->member['uid']])->find();
        $this->assign("list", $list);
        $this->siteFetch('member/setting');
    }

    //提交设置
    public function doSetting(){
        $data = request()->param();
        Db::table('xj_member')->where(['uid'=>$this->member['uid']])->update($data);
        return arraySuccess('客官,成功了!!!');
    }

    public function uploadImg()
    {
        try {
            // 获取上传文件
            $file = request()->file('file');

            // 验证文件是否存在
            if (empty($file)) {
                return json(['status' => 0, 'info' => '请选择要上传的图片']);
            }

            // 验证文件大小和类型
//            $validate = [
//                'size' => 1024 * 1024 * 2, // 限制2M
//                'ext'  => 'jpg,jpeg,png,gif'
//            ];
//
//            // 验证文件
//            $check = $file->validate($validate)->check();
//            if (!$check) {
//                return json(['status' => 0, 'info' => $file->getError()]);
//            }

            // 生成保存路径
            $savePath = 'upload/avatar/' . date('Ymd') . '/';
            $saveName = md5(uniqid()) . '.' . $file->extension();

            // 移动文件到指定目录
            $info = $file->move(public_path() . $savePath, $saveName);
            if (!$info) {
                return json(['status' => 0, 'info' => '文件上传失败']);
            }
            // 获取文件路径
            $filePath = $savePath . $saveName;
            $data['url']='/' . $filePath ;
            return arraySuccess('客官,成功了!!!',$data);
        } catch (\Exception $e) {
            // 捕获异常并返回错误信息
            return arrayFail('客官，,这家伙不肯这么做！！！');
        }
    }

    public function headUpload()
    {
        try {
            // 获取上传文件
            $file = request()->file('file');

            // 验证文件是否存在
            if (empty($file)) {
                return json(['status' => 0, 'info' => '请选择要上传的图片']);
            }

            // 验证文件大小和类型
//            $validate = [
//                'size' => 1024 * 1024 * 2, // 限制2M
//                'ext'  => 'jpg,jpeg,png,gif'
//            ];
//
//            // 验证文件
//            $check = $file->validate($validate)->check();
//            if (!$check) {
//                return json(['status' => 0, 'info' => $file->getError()]);
//            }

            // 生成保存路径
            $savePath = 'upload/avatar/' . date('Ymd') . '/';
            $saveName = md5(uniqid()) . '.' . $file->extension();

            // 移动文件到指定目录
            $info = $file->move(public_path() . $savePath, $saveName);
            if (!$info) {
                return json(['status' => 0, 'info' => '文件上传失败']);
            }

            // 获取文件路径
            $filePath = $savePath . $saveName;

            $data['avatar']='/' . $filePath ;
            Db::table('xj_member')->where(['uid'=>$this->member['uid']])->update($data);
            return arraySuccess('客官,成功了!!!',$data);
        } catch (\Exception $e) {
            // 捕获异常并返回错误信息
            return arrayFail('客官，,这家伙不肯这么做！！！');
//            return json([
//                'status' => 0,
//                'info'   => '上传失败: ' . $e->getMessage()
//            ]);
        }
    }



}